/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:CommodityServiceImpl.java
 * Version:1.0
 * Date:2011-12-10
 * Description: 
 * author:TT_LOVE
 */
package com.tietiao.service.commodity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tietiao.common.constants.CommodityConstants;
import com.tietiao.common.constants.LogConstants;
import com.tietiao.common.constants.SysUserConstants;
import com.tietiao.common.util.PageModel;
import com.tietiao.common.util.StringUtil;
import com.tietiao.dao.CommodityInfoMapper;
import com.tietiao.dao.MidLableCommodityMapper;
import com.tietiao.dao.TietiaoMapper;
import com.tietiao.dao.model.CommodityInfo;
import com.tietiao.dao.model.CommodityInfoCriteria;
import com.tietiao.dao.model.Lable;
import com.tietiao.dao.model.MidLableCommodity;
import com.tietiao.dao.model.SysMessage;
import com.tietiao.dao.model.SysUser;
import com.tietiao.dao.model.Tietiao;
import com.tietiao.dao.model.UserComment;
import com.tietiao.dao.model.UserCommidityFavorite;
import com.tietiao.service.bean.CommodityBean;
import com.tietiao.service.bean.FriendBean;
import com.tietiao.service.comment.CommentService;
import com.tietiao.service.label.LabelService;
import com.tietiao.service.syslog.SysLogService;
import com.tietiao.service.sysmessage.SysMessageService;
import com.tietiao.service.sysuser.SysUserService;
import com.tietiao.service.tietiao.TietiaoService;

@Service
public class CommodityServiceImpl implements CommodityService {

	@Resource
	private CommodityInfoMapper commodityInfoMapper;
	@Resource
	private SysLogService sysLogService;
	@Resource
	private LabelService labelService;
	@Resource
	private MidLableCommodityMapper midLableCommodityMapper;
	@Resource
	private CommentService commentService;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysMessageService sysMessageService;
	@Resource
	private TietiaoMapper tietiaoMapper;
	@Resource
	private TietiaoService tietiaoService;
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tietiao.service.commodity.CommodityService#
	 * findCommodityInfoListByCondition(com.tietiao.service.bean.CommodityBean)
	 */
	@Override
	public List<CommodityInfo> findCommodityInfoListByCondition(
			CommodityBean commodityBean) {
		CommodityInfoCriteria criteria = new CommodityInfoCriteria();
		criteria.createCriteria().andCommodityIdEqualTo(
				commodityBean.getCommodityInfo().getCommodityId());
		return commodityInfoMapper.selectByExample(criteria);
	}

	@Override
	public CommodityInfo getCommodityInfoByCommodityId(int commodityId,
			Integer loginUserId) {
		return commodityInfoMapper.selectCommodityInfoByCommodityId(commodityId, loginUserId);
	}

	@Override
	public CommodityInfo getCommodityInfoByCommodityId(int commodityId) {
		CommodityInfoCriteria criteria = new CommodityInfoCriteria();

		criteria.createCriteria().andCommodityIdEqualTo(commodityId);

		return commodityInfoMapper.selectByPrimaryKey(commodityId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#getCommodityInfoByCondition
	 * (com.tietiao.service.bean.CommodityBean)
	 */
	@Override
	public int getCommodityInfoByCondition(CommodityBean commodityBean) {
		CommodityInfoCriteria criteria = new CommodityInfoCriteria();
		criteria.createCriteria().andCategoyrNameLike(
				commodityBean.getCommodityInfo().getCategoyrName());
		criteria.createCriteria().andUploaderTimeBetween(
				commodityBean.getBeginTime(), commodityBean.getEndTime());
		return commodityInfoMapper.countByExample(criteria);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tietiao.service.commodity.CommodityService#getPageModel(int,
	 * int, com.tietiao.service.bean.CommodityBean)
	 */
	@Override
	public PageModel<CommodityInfo> getPageModel(int pageSize, int pageNum,
			CommodityBean commodityBean) {
		CommodityInfoCriteria criteria = new CommodityInfoCriteria();
		pageNum = pageNum < 1 ? 1 : pageNum;// 最小值为一页
		criteria.setStart(pageSize * (pageNum - 1));
		criteria.setLimit(pageSize * pageNum);
		criteria.createCriteria().andCategoyrNameLike(
				commodityBean.getCommodityInfo().getCategoyrName());
		criteria.createCriteria().andUploaderTimeBetween(
				commodityBean.getBeginTime(), commodityBean.getEndTime());
		List<CommodityInfo> lists = commodityInfoMapper
				.selectByExample(criteria);
		int count = commodityInfoMapper.countByExample(criteria);
		return new PageModel<CommodityInfo>(lists, pageNum, pageSize, count);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#insertCommodityInfo(com
	 * .tietiao.service.bean.CommodityBean)
	 */
	@Override
	public int insertCommodityInfo(CommodityBean commodityBean) {
		int id = commodityInfoMapper.insert(commodityBean.getCommodityInfo());
		// sysLogService.insertSysLog(LogConstants.OP_TYPE_INSERT, "添加商品信息",
		// "添加商品标签为" + commodityBean.getCommodityInfo().getTitle()
		// + "的商品信息！");
		return id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#updateCommodityInfo(com
	 * .tietiao.service.bean.CommodityBean)
	 */
	@Override
	public int updateCommodityInfo(CommodityBean commodityBean) {
		int id = commodityInfoMapper.insert(commodityBean.getCommodityInfo());
		sysLogService.insertSysLog(LogConstants.OP_TYPE_INSERT, "更新商品信息",
				"更新商品编号为：" + commodityBean.getCommodityInfo().getCategoryId()
						+ "的商品信息！");
		return id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#shareCommdityInfo(com.
	 * tietiao.service.bean.CommodityBean)
	 */
	@Override
	@Transactional
	public int shareCommdityInfo(CommodityBean commodityBean) {

		CommodityInfo commodityInfo = commodityBean.getCommodityInfo();

		String picName = commodityInfo.getPicPath().substring(0,
				commodityInfo.getPicPath().indexOf("."));
		String suffix = commodityInfo.getPicPath().substring(
				commodityInfo.getPicPath().indexOf("."));
		commodityInfo.setQietuOne(picName + "one" + suffix);
		// 判断是否切第二个图
		if (CommodityConstants.QIETU_TWO_HEIGHT != 0
				&& CommodityConstants.QIETU_TWO_WIDTH != 0) {
			commodityInfo.setQietuTwo(picName + "two" + suffix);
		}
		commodityInfo.setTietiaoNum(0);
		commodityInfoMapper.insert(commodityInfo);
		int commdityId = commodityInfo.getCommodityId();
		// 添加标签
		if (StringUtil.checkStrIsNotNull(commodityInfo.getLables())) {
			String labelIds = labelService.addLabels(commodityBean
					.getCommodityInfo().getUploaderId(), commodityBean
					.getCommodityInfo().getLables());
			batchAddMidLableCommidtys(commdityId, labelIds);
		}
		// 加入至收藏夹中
		Tietiao tietiao = new Tietiao();
		tietiao.setCommodityId(commdityId);
		tietiao.setUserId(commodityBean.getCommodityInfo().getUploaderId());
		tietiao.setFavoriteId(commodityBean.getFavoriteId());
		tietiao.setTietiaoTime(new Date());
		tietiao.setIsShare(1);
		tietiaoService.addTieTiao(tietiao);
		return commdityId;
	}

	/**
	 * 
	 * 功能：批量加入标签商品中间表信息
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-14
	 * 
	 * @param commdityId
	 * @param labelIds
	 */
	private void batchAddMidLableCommidtys(int commdityId, String labelIds) {
		String[] lableArr = labelIds.split(",");
		List<MidLableCommodity> midLableCommodities = new ArrayList<MidLableCommodity>();
		for (String lableId : lableArr) {
			MidLableCommodity midLableCommodity = new MidLableCommodity();
			midLableCommodity.setCommodityId(commdityId);
			midLableCommodity.setLabelId(Integer.valueOf(lableId));
			midLableCommodities.add(midLableCommodity);
		}
		midLableCommodityMapper.batchInsert(midLableCommodities);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#searchCommodityInfos(java
	 * .lang.String, java.lang.Integer, java.util.Date, java.lang.Integer,
	 * java.lang.String)
	 */
	@Override
	public List<CommodityInfo> searchCommodityInfos(String lableName,
			Integer minTietiaoNum, Date minCreateDate, Integer loginUserId,
			Integer start, Integer limit, String orderByClause) {
		boolean notInFlag = false;
		// 查询全部
		if ("all".equals(lableName) || StringUtil.strIsNull(lableName)) {
			lableName = null;
		} else if (lableName.indexOf(",") > 0) {
			notInFlag = true;
			lableName = StringUtil.wrapSqlInCondition(lableName);
		}
		List<CommodityInfo> result = commodityInfoMapper
				.selectHotLableCommodityInfos(lableName, notInFlag,
						minTietiaoNum, minCreateDate, loginUserId, start,
						limit, orderByClause);
		return result;
	}

	/**
	 * 
	 * 功能：批量更新商品被贴条数
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-22
	 * 
	 * @param addTietiaoNumFlag
	 *            true 被贴条数 + 1 false 被贴条数 - 1
	 * 
	 * @param commodityInfos
	 *            商品ID数组
	 * @return
	 */
	public int batchUpdateTietiaoNum(boolean addTietiaoNumFlag,
			String[] commodityIds) {

		if (commodityIds == null || commodityIds.length == 0) {
			return 0;
		}
		StringBuilder sbIds = new StringBuilder();
		for (int i = 0; i < commodityIds.length; i++) {
			sbIds.append(commodityIds[i]);
			if (i < commodityIds.length - 1) {
				sbIds.append(",");
			}
		}
		return commodityInfoMapper.bUTietiaoNum(addTietiaoNumFlag,
				sbIds.toString());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tietiao.service.commodity.CommodityService#getPageModel(int,
	 * int, com.tietiao.service.bean.FriendBean)
	 */
	@Override
	public PageModel<CommodityInfo> getPageModel(int pageSize, int pageNum,
			FriendBean bean) {
		pageNum = pageNum < 1 ? 1 : pageNum;// 最小值为一页
		bean.setStart(pageSize * (pageNum - 1));
		bean.setLimit(pageSize * pageNum);
		List<CommodityInfo> lists = commodityInfoMapper
				.selectCommodityInfo(bean);
		int count = commodityInfoMapper.selectCommodityInfoCount(bean);
		return new PageModel<CommodityInfo>(lists, pageNum, pageSize, count);
	}

	@Override
	public List<CommodityInfo> getTieTiaoCommodityInfo(int start, int limit,
			Integer userId, Integer uploaderId, Integer favoriteId,
			Integer loginUserId, String orderBy) {
		return commodityInfoMapper.getTieTiaoCommodityInfo(start, limit,
				userId, uploaderId, favoriteId, loginUserId, orderBy);
	}

	@Override
	public int getTieTiaoNum(Integer userId, Integer upLoaderId,
			Integer favoriteId) {
		return commodityInfoMapper
				.getTieTiaoNum(userId, upLoaderId, favoriteId);
	}

	@Override
	public PageModel<CommodityInfo> getPageModelCommodityInfosForBg(
			CommodityInfo commodityInfo, Integer start, Integer limit,
			String sort, String dir) {
		List<CommodityInfo> commodityInfos = commodityInfoMapper
				.selectBgCommoditys(commodityInfo, start, limit,
						StringUtil.wrapSort(sort, dir));
		int count = commodityInfoMapper.selectBgCommodityCounts(commodityInfo);
		return new PageModel<CommodityInfo>(commodityInfos, count);
	}

	@Override
	public void delCommodityForBg(String commodityIds) {
		commodityInfoMapper.delCommoditys(commodityIds);
	}

	@Override
	public List<CommodityInfo> getMyFavoriteLableComm(int start, int limit,
			String lableName, Integer loginUserId, Integer userId,
			String orderBy) {
		return commodityInfoMapper.getMyFavoriteLableComm(start, limit,
				lableName, loginUserId, userId, orderBy);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#getCommentInfoByCommodityId
	 * (int)
	 */
	@Override
	public List<UserComment> getCommentInfoByCommodityId(int commodityId,
			String orderType, int parentCommentId) {

		return commentService.getCommentInfoByCommodityId(commodityId,
				orderType, parentCommentId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#searchCommodityInfoByLable
	 * (java.util.List, java.lang.String)
	 */
	@Override
	public List<CommodityInfo> searchCommodityInfoByLable(String lables,
			Integer loginUserId, Integer start, Integer limit, String orderType) {
		String[] lableArr = lables.split(" ");
		String lableNames = StringUtil.wrapSqlInCondition(lableArr, true);
		return commodityInfoMapper.searchCommodityInfoByLable(lableNames,
				loginUserId, start, limit, orderType);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#getCommendUser(java.lang
	 * .Integer)
	 */
	@Override
	public List<SysUser> getCommendUser(Integer userId, String petName) {
		// TODO Auto-generated method stub
		return sysUserService.selectFriendsUser(0, 0, userId, null, petName, null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#sendCommodityInfoToCommendUser
	 * (int, java.lang.String[])
	 */
	@Override
	public void sendCommodityInfoToCommendUser(int commodityId,
			String[] userIdArr, SysUser loginUser, String webRoot) {
		SysMessage message = new SysMessage();
		message.setMessageType(SysUserConstants.MESSAGE_TYPE_RECOMMEND);
		message.setUserId(loginUser.getUserId());
		message.setMessage(loginUser.getPetName() + "向您推荐一条商品信息：" + webRoot
				+ "/index_commodity_commodityDetail.htm?commodityId="
				+ commodityId);
		message.setIsValid(1);
		message.setCreateTime(new Date());
		sysMessageService.addSysMessage(message, userIdArr);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#submitComment(com.tietiao
	 * .dao.model.SysUser, int, java.lang.String)
	 */
	@Override
	public void submitComment(SysUser loginUser, int commodityId,
			String commentInfo) {
		commentService.addUserComment(commentInfo, loginUser, commodityId, -1);
	}

	@Override
	public List<CommodityInfo> searchCommodityInfos(String title,
			Integer loginUserId, Integer start, Integer limit,
			String orderByclause) {
		return commodityInfoMapper.selectCommodityByTitle(title, loginUserId,
				start, limit, orderByclause);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tietiao.service.commodity.CommodityService#
	 * searchCommodityInfoByFavoriteInfo
	 * (com.tietiao.dao.model.UserCommidityFavorite, java.lang.Integer,
	 * java.lang.Integer, java.lang.Integer, java.lang.String)
	 */
	@Override
	public List<CommodityInfo> searchCommodityInfoByFavoriteInfo(
			UserCommidityFavorite userCommidityFavorite, Integer logUserId,
			Integer start, Integer limit, String orderType) {

		return commodityInfoMapper.searchCommodityInfoByFavoriteInfo(
				userCommidityFavorite, logUserId, start, limit, orderType);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#submitContentInfo(com.
	 * tietiao.dao.model.SysUser, int, java.lang.String, java.lang.String)
	 */
	@Override
	public void submitContentInfo(SysUser loginUser, int commodityId,
			String commentId, String contentInfo) {
		commentService.addContentInfo(loginUser, commodityId, commentId,
				contentInfo);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tietiao.service.commodity.CommodityService#searchCommodityInfoByUserId
	 * (java.lang.Integer, java.lang.String)
	 */
	@Override
	public List<CommodityInfo> searchCommodityInfoByUserId(Integer logUserId,
			String orderType) {

		return commodityInfoMapper.searchCommodityInfoByUserId(logUserId,
				orderType);
	}

	@Override
	public int getMyFavComNum(int userId) {
		return tietiaoMapper.selectMyFavCommNum(userId);
	}

	/* (non-Javadoc)
	 * @see com.tietiao.service.commodity.CommodityService#getLableInfoList()
	 */
	@Override
	public List<Lable> getLableInfoList() {
		
		return labelService.getLabelInfo();
	}
}
